<template>
  <div class="venus-list-page">
    <!--签约查询界面-->
    <div class="page-search">
      <!--:rules prop 如果不要校验那么这个属性可以不填-->
      <el-form
        label-width="160px"
        size="mini"
      >
        <el-row>
          <!--流程名-->
          <el-col :span="8">
            <el-form-item label="流程名:" style="margin-bottom: 10px;">
              <el-select
                v-model="table.bean_table.processName"
                class="venus-input-middle"
                filterable
                clearable
                placeholder="--请选择--"
              >
                <el-option
                  v-for="(item) in dict.processName"
                  :key="item.id"
                  :label="item.text"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!--状态-->
          <el-col :span="8">
            <el-form-item label="状态:" style="margin-bottom: 10px;">
              <el-select
                v-model="table.bean_table.status"
                class="venus-input-middle"
                filterable
                clearable
                placeholder="--请选择--"
              >
                <el-option
                  v-for="(item) in dict.status"
                  :key="item.id"
                  :label="item.text"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div style="text-align: center;margin-bottom: 10px;">
          <el-button type="success" @click="search" size="mini">查询</el-button>
          <el-button type="info" plain @click="resetForm" size="mini">重置</el-button>
          <el-button type="success" @click="addBean" size="mini">新增</el-button>
        </div>
      </el-form>
    </div>
    <!-- 查询列表返显 -->
    <div class="page-list">
      <table-pagination
        :table-data="table.bean_table.tableData"
        :table-header-config="table.tableHeaderConfig"
        :operation-config="table.operationConfig"
        highlight-current-row
        :total="table.bean_table.total"
        :page-size="table.bean_table.limit"
        :now-page="table.bean_table.nowPage"
        @current-change="currentChange"
        :dict-data="dict"
      />
    </div>

    <!--新增弹出框-->
    <el-dialog :title="dialog.add.title" :visible.sync="dialog.add.formVisible">
      <!-- ref=dlgForm用于验证表单 -->
      <el-form ref="dlgFormAdd" :model="dialog.form" size="mini">
        <el-input type="hidden" v-model="dialog.form.id" />
        <el-row>
          <!--流程名-->
          <el-col :xs="24" :sm="12" :md="12">
            <!-- prop,:rules必须一起写 -->
            <el-form-item
              label="流程名"
              :label-width="dialog.formLabelWidth"
              prop="processName"
              :rules="dialog.formRules.processName"
            >
              <el-select
                v-model="dialog.form.processName"
                placeholder="请选择流程名"
                filterable
                clearable
              >
                <el-option
                  v-for="item in dict.processName"
                  :key="item.id"
                  :label="item.text"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!--代理人-->
          <el-col :xs="24" :sm="12" :md="12">
            <el-form-item
              label="代理人"
              :label-width="dialog.formLabelWidth"
              prop="surrogate"
              :rules="dialog.formRules.surrogate"
            >
              <el-select
                v-model="dialog.form.surrogate"
                placeholder="请选择代理人"
                filterable
                clearable
              >
                <el-option
                  v-for="item in dict.surrogate"
                  :key="item.id"
                  :label="item.text"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!--开始时间-->
          <el-col :xs="24" :sm="12" :md="12">
            <el-form-item
              label="开始时间"
              :label-width="dialog.formLabelWidth"
              prop="startDate"
              :rules="dialog.formRules.startDate"
            >
              <el-date-picker
                v-model="dialog.form.startDate"
                type="date"
                value-format="yyyyMMdd"
                placeholder="请输入开始时间"
              />
            </el-form-item>
          </el-col>
          <!--结束时间-->
          <el-col :xs="24" :sm="12" :md="12">
            <el-form-item
              label="结束时间"
              :label-width="dialog.formLabelWidth"
              prop="endDate"
              :rules="dialog.formRules.endDate"
            >
              <el-date-picker
                v-model="dialog.form.endDate"
                type="date"
                value-format="yyyyMMdd"
                placeholder="请输入结束时间"
              />
            </el-form-item>
          </el-col>
          <!--状态-->
          <el-col :xs="24" :sm="12" :md="12">
            <el-form-item
              label="状态"
              :label-width="dialog.formLabelWidth"
            >
              <el-select
                v-model="dialog.form.status"
                placeholder="请选择状态"
                filterable
                clearable
                disabled
              >
                <el-option
                  v-for="item in dict.status"
                  :key="item.id"
                  :label="item.text"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="success" @click="addOk" size="mini">确 定</el-button>
        <el-button type="info" plain @click="dialog.add.formVisible=false" size="mini">取 消</el-button>
      </div>
    </el-dialog>
    <!--修改弹出框-->
    <el-dialog :title="dialog.edit.title" :visible.sync="dialog.edit.formVisible">
      <!-- ref=dlgForm用于验证表单 -->
      <el-form ref="dlgFormEdit" :model="dialog.form" size="mini">
        <el-input type="hidden" v-model="dialog.form.id" />
        <el-row>
          <!--流程名-->
          <el-col :xs="24" :sm="12" :md="12">
            <!-- prop,:rules必须一起写 -->
            <el-form-item
              label="流程名"
              :label-width="dialog.formLabelWidth"
              prop="processName"
              :rules="dialog.formRules.processName"
            >
              <el-select
                v-model="dialog.form.processName"
                placeholder="请选择流程名"
                filterable
                clearable
              >
                <el-option
                  v-for="item in dict.processName"
                  :key="item.id"
                  :label="item.text"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!--代理人-->
          <el-col :xs="24" :sm="12" :md="12">
            <el-form-item
              label="代理人"
              :label-width="dialog.formLabelWidth"
              prop="surrogate"
              :rules="dialog.formRules.surrogate"
            >
              <el-select
                v-model="dialog.form.surrogate"
                placeholder="请选择代理人"
                filterable
                clearable
              >
                <el-option
                  v-for="item in dict.surrogate"
                  :key="item.id"
                  :label="item.text"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!--开始时间-->
          <el-col :xs="24" :sm="12" :md="12">
            <el-form-item
              label="开始时间"
              :label-width="dialog.formLabelWidth"
              prop="startDate"
              :rules="dialog.formRules.startDate"
            >
              <el-date-picker
                v-model="dialog.form.startDate"
                type="date"
                value-format="yyyyMMdd"
                editable
                placeholder="请输入开始时间"
              />
            </el-form-item>
          </el-col>
          <!--结束时间-->
          <el-col :xs="24" :sm="12" :md="12">
            <el-form-item
              label="结束时间"
              :label-width="dialog.formLabelWidth"
              prop="endDate"
              :rules="dialog.formRules.endDate"
            >
              <el-date-picker
                v-model="dialog.form.endDate"
                type="date"
                value-format="yyyyMMdd"
                placeholder="请输入结束时间"
              />
            </el-form-item>
          </el-col>
          <!--状态-->
          <el-col :xs="24" :sm="12" :md="12">
            <el-form-item
              label="状态"
              :label-width="dialog.formLabelWidth"
              prop="status"
              :rules="dialog.formRules.status"
            >
              <el-select
                v-model="dialog.form.status"
                placeholder="请选择状态"
                filterable
                clearable
              >
                <el-option
                  v-for="item in dict.status"
                  :key="item.id"
                  :label="item.text"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="success" @click="editOk" size="mini">确 定</el-button>
        <el-button type="info" plain @click="dialog.edit.formVisible=false" size="mini">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  /* 自定义数据加载 */
  import request from '../../../utils/request.js'
  import * as kk from '../../../utils/k-utils.js'

  export default {
    name: 'Surrogate',
    data() { // 数据定义
      return {
        /* 字典 */
        dict: {
          processName: [], // 流程名
          surrogate: [], // 代理人
          status: [] // 状态
        },
        /* 表格 */
        table: {
          // 表头配置
          tableHeaderConfig: [
            // { prop: 'order', label: '序号' },
            { prop: 'processDisplayName', label: '流程名' },
            { prop: 'startDate', label: '开始时间' },
            { prop: 'endDate', label: '结束时间' },
            { prop: 'creator', label: '授权人' },
            { prop: 'surrogate', label: '代理人' },
            { prop: 'status', label: '状态' }
          ],
          operationConfig: { // 表格操作配置
            fixed: 'right',
            width: 200,
            operationButton: [
              // 每一个操作。value:操作文字；func:回调函数
              { value: '修改', func: this.myModify },
              { value: '删除', func: this.myDelete },
              { value: '启动', func: this.myEnable },
              { value: '禁用', func: this.myDisable }
            ]
          },
          bean_table: {
            total: 0, // 总条数
            nowPage: 1, // 当前第几页
            limit: 5, // 分页配置
            tableData: [], // 表格数据
            // exeid: 'queryTrustInfo', // exeid
            // 查询条件
            processName: '', // 流程名
            status: '' // 状态
          }
        },
        /* ===========新增，修改，详情=============== */
        dialog: {
          formLabelWidth: '100px',
          formRules: {
            processName: [
              { required: true, message: '请选择流程名', trigger: 'change' }
            ],
            surrogate: [
              { required: true, message: '请选择代理人', trigger: 'change' }
            ],
            startDate: [
              { required: true, message: '请选择开始时间', trigger: 'change' }
            ],
            endDate: [
              { required: true, message: '请选择结束时间', trigger: 'change' }
            ],
            status: [
              { required: true, message: '请选择状态', trigger: 'change' }
            ]
          },
          form: {
            id: '', // 主键
            processName: '', // 流程名
            surrogate: '', // 代理人
            startDate: '', // 开始时间
            endDate: '', // 结束时间
            status: '' // 状态
          },
          add: {
            title: '新增转审批',
            formVisible: false
          },
          edit: {
            title: '修改转审批',
            formVisible: false
          }
        }
      }
    },
    mounted() {
      // 初始化调用
      this.init()
    },
    methods: {
      // 页面初始化
      init: function() {
        /* 加载字典 */
        // 流程名
        this.load_dict_url(this, '/workflow/process/select2/allProcessNames.json', 'processName')
        // 代理人
        this.load_dict_url(this, '/workflow/web3api/user/select2.json', 'surrogate')
        // 审核类型
        this.dict.status = [
          { id: '0', text: '禁用' },
          { id: '1', text: '启用' }
        ]
        /* 加载表格数据 */
        this.table.bean_table.nowPage = 1 // 初始第一页
        this.load_table_url(this, '/workflow/surrogate/list.json', 'bean_table', 'workflow')
      },
      /* 通过url加载字典 */
      load_dict_url(this_object, url, dict) {
        request({
          loading: true,
          url: url,
          method: 'post'
        }).then(rep => {
          // rep接收到的是字符串
          if (typeof rep === 'string') {
            rep = JSON.parse(rep)
          }
          for (var key in rep) {
            this_object['dict'][dict].push(rep[key])
          }
        })
      },
      /* 通过url加载表格 */
      load_table_url(this_object, url, params_name) {
        this_object['table'][params_name].offset = (this_object['table'][params_name].nowPage - 1) * this_object['table'][params_name].limit// 后台分页参数
        this_object['table'][params_name].tableData = []// 清空原来的旧数据
        this_object['table'][params_name].order = 'asc'
        return request({
          loading: true,
          url: url,
          method: 'post',
          params: this_object['table'][params_name]// 请求参数
        }).then(rep => {
          // rep接收到的是字符串
          if (typeof rep === 'string') {
            rep = JSON.parse(rep)
          }
          // 格式化显示时间
          for (var i = 0; i < rep.rows.length; i++) {
            rep.rows[i].startDate = kk.dateFormat(rep.rows[i].startDate)
            rep.rows[i].endDate = kk.dateFormat(rep.rows[i].endDate)
          }
          this_object['table'][params_name].total = rep.total// 获取总条数
          this_object['table'][params_name].tableData = rep.rows// 获取返回数据
        })
      },
      // 事件触发
      search() { // 查询函数
        this.table.bean_table.nowPage = 1 // 初始第一页
        this.load_table_url(this, '/workflow/surrogate/list.json', 'bean_table', 'workflow')
      },
      // 重置
      resetForm() {
        this.table.bean_table.processName = ''// 流程名
        this.table.bean_table.status = ''// 状态
      },
      // 下一页触发的事件
      currentChange(index) {
        this.table.bean_table.nowPage = index // 初始第一页
        this.load_table_url(this, '/workflow/surrogate/list.json', 'bean_table', 'workflow')
      },
      // ======================弹出框======================
      // 将obj1对象的数据拷贝到obj对象
      copyObj(obj1, obj2) {
        for (var key in obj1) {
          if (key === '__proto__') {
            continue
          }
          // 不存在的属性不拷贝
          if (!obj2.hasOwnProperty(key)) {
            continue
          }
          // 自动将number转换成string
          if (typeof obj1[key] === 'number') {
            obj1[key] = '' + obj1[key]
          }
          obj2[key] = obj1[key]
        }
      },
      copyObj2(obj1, obj2) {
        for (var key in obj1) {
          if (key === '__proto__') {
            continue
          }
          // 自动将number转换成string
          if (typeof obj1[key] === 'number') {
            obj1[key] = '' + obj1[key]
          }
          obj2[key] = obj1[key]
        }
      },
      // 数组通过属性查找 例如 arr = [obj,obj]
      findWhere(arr, obj) {
        for (var i = 0; i < arr.length; i++) {
          for (var key in obj) {
            // key相等,value也相等
            if (arr[i].hasOwnProperty(key) && arr[i][key] === obj[key]) {
              return arr[i]
            }
          }
        }
        return {}
      },
      /* -----------新增---------- */
      // 新增
      addBean() {
        // 清空数据
        this.copyObj({
          id: '', // 主键
          processName: '', // 流程名
          surrogate: '', // 代理人
          startDate: '', // 开始时间
          endDate: '', // 结束时间
          status: '1' // 状态 1启用0禁用
        }, this.dialog.form)
        this.$nextTick(() => {
          // 重复新增，去掉校验提示
          this.$refs.dlgFormAdd.clearValidate() // 必须写在$nextTick里面
        })
        this.dialog.add.formVisible = true
      },
      // 新增确认
      addOk() {
        var _this = this
        this.$refs.dlgFormAdd.validate((valid) => {
          if (valid) {
            _this.addOkHandler()
          } else {
            console.log('表单数据检验没有全部通过！！')
          }
        })
      },
      addOkHandler() {
        var _this = this
        var bean = {}
        this.copyObj2(this.dialog.form, bean)
        bean.startDate = bean.startDate.replace(/-/g, '')
        bean.endDate = bean.endDate.replace(/-/g, '')
        bean.processName_displaylable = this.findWhere(this.dict.processName, { id: bean.processName }).text
        bean.surrogate_displaylable = this.findWhere(this.dict.surrogate, { id: bean.surrogate }).text
        var url = '/surrogate/save.json'
        kk.k_load_url('workflow', url, bean).then(rep => {
          rep = JSON.parse(rep)
          if (rep.status === '200') {
            _this.search()
            _this.$message(rep.data)
            // 关闭弹出框
            _this.dialog.add.formVisible = false
          } else {
            _this.$message(rep.message)
          }
        })
      },
      /* -----------修改---------- */
      // 修改
      myModify(item, index) {
        // 清空数据
        this.copyObj(item, this.dialog.form)
        this.$nextTick(() => {
          // 重复新增，去掉校验提示
          this.$refs.dlgFormEdit.clearValidate() // 必须写在$nextTick里面
        })
        this.dialog.edit.formVisible = true
      },
      // 修改确认
      editOk() {
        var _this = this
        this.$refs.dlgFormEdit.validate((valid) => {
          if (valid) {
            _this.editOkHandler()
          } else {
            console.log('表单数据检验没有全部通过！！')
          }
        })
      },
      editOkHandler() {
        var _this = this
        var bean = {}
        this.copyObj2(this.dialog.form, bean)
        bean.startDate = bean.startDate.replace(/-/g, '')
        bean.endDate = bean.endDate.replace(/-/g, '')
        bean.processName_displaylable = this.findWhere(this.dict.processName, { id: bean.processName }).text
        bean.surrogate_displaylable = this.findWhere(this.dict.surrogate, { id: bean.surrogate }).text
        var url = '/surrogate/update.json'
        kk.k_load_url('workflow', url, bean).then(rep => {
          rep = JSON.parse(rep)
          if (rep.status === '200') {
            _this.search()
            _this.$message(rep.data)
            // 关闭弹出框
            _this.dialog.edit.formVisible = false
          } else {
            _this.$message(rep.message)
          }
        })
      },
      // ======================表格======================
      /* 删除 */
      myDelete(item, index) {
        var _this = this
        this.$confirm('确认删除吗?', '提示', {})
          .then(() => {
            var url = '/surrogate/remove.json?id=' + item.id
            kk.k_load_url('workflow', url, {}).then(rep => {
              rep = JSON.parse(rep)
              if (rep['status'] === '200') {
                _this.search()
                _this.$message('删除成功')
              } else {
                _this.$message('删除失败')
              }
            })
          })
          .catch(() => { /* 用户取消注销 */ })
      },
      /* 启用 */
      myEnable(item, index) {
        var _this = this
        this.$confirm('确认启用吗?', '提示', {})
          .then(() => {
            var url = '/surrogate/enable.json?id=' + item.id
            kk.k_load_url('workflow', url, {}).then(rep => {
              rep = JSON.parse(rep)
              if (rep['status'] === '200') {
                _this.search()
                _this.$message('启用成功')
              } else {
                _this.$message('启用失败')
              }
            })
          })
          .catch(() => { /* 用户取消注销 */ })
      },
      /* 禁用 */
      myDisable(item, index) {
        var _this = this
        this.$confirm('确认禁用吗?', '提示', {})
          .then(() => {
            var url = '/surrogate/disable.json?id=' + item.id
            kk.k_load_url('workflow', url, {}).then(rep => {
              rep = JSON.parse(rep)
              if (rep['status'] === '200') {
                _this.search()
                _this.$message('禁用成功')
              } else {
                _this.$message('禁用失败')
              }
            })
          })
          .catch(() => { /* 用户取消注销 */ })
      }
    }
  }
</script>

<style scoped>
  /*让文本可以被选中*/
  .venus-list-page {
    -moz-user-select: text; /*火狐*/
    -webkit-user-select: text; /*webkit浏览器*/
    -ms-user-select: text; /*IE10*/
    -khtml-user-select: text; /*早期浏览器*/
    user-select: text;
  }
</style>
